﻿#include "itemedit.h"
#include "ui_itemedit.h"

ItemEdit::ItemEdit(int id, QWidget *parent, const QString &table) :
    _id(id),
    _table(table),
    QDialog(parent),
    ui(new Ui::ItemEdit)
{
    ui->setupUi(this);

    initView();
}

ItemEdit::~ItemEdit()
{
    delete ui;
}

void ItemEdit::initView()
{
    QSqlQuery query;
    QString sql=QString("select * from %1 where id=%2").arg(_table).arg(_id);
    query.exec(sql);
    if(query.next())
    {
        _category=query.value("category").toString();
        _label=query.value("label").toString();
        _detail=query.value("detail").toString();

        ui->category->setText(_category);
        ui->label->setText(_label);
        ui->detail->setPlainText(_detail);
    }
}

void ItemEdit::on_btn_save_clicked()
{
    QString category=ui->category->text().trimmed();
    if(category.isEmpty())
        return;

    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
        return;

    QString detail=ui->detail->toPlainText();
    if(detail.isEmpty())
        return;

    if(category == _category && label == _label && detail == _detail)
        return;

    QString sql=QString("update %1 set category = '%2',label='%3',detail='%4' where id=%5")
            .arg(_table)
            .arg(category)
            .arg(label)
            .arg(detail)
            .arg(_id);

    QSqlQuery query;
    if(!query.exec(sql))
        QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法保存！"));
    else
        this->accept();
}
